﻿using System;
using System.Web.Mvc;
using System.Web.Script.Serialization;

namespace Fuse8.ContentManagementFramework.Web.MvcPowered
{
    public class FromJsonAttribute : CustomModelBinderAttribute
    {
        public override IModelBinder GetBinder()
        {
            return new JsonModelBinder();
        }        
    }

    internal class JsonModelBinder : IModelBinder
    {
        private readonly static JavaScriptSerializer _serializer = new JavaScriptSerializer();

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string stringified = controllerContext.HttpContext.Request[bindingContext.ModelName];

            return !string.IsNullOrEmpty(stringified) ?
                _serializer.Deserialize(stringified, bindingContext.ModelType) :
                null;
        }
    }
}
